package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;// 获取存储服务器的请求URL

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 发布视频
     * @param videoThumbnail    封面图片
     * @param videoFile         上传文件
     */
    @CacheEvict(value = "videos",allEntries = true)
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        if (videoFile.isEmpty() || videoThumbnail.isEmpty()){
            throw new BusinessException(ErrorResult.error());
        }
        //1.将视频文件上传到fastDFS,获取访问地址
        String filename = videoFile.getOriginalFilename();
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //2.将封面图片上传到阿里云oss,获取访问地址URL
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //3.构建videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("你好这是一个视频");
        //4.调用API保存数据
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)){
            throw new BusinessException(ErrorResult.error());
        }
    }

    /**
     * 视频列表展示
     * @param page
     * @param pagesize
     * @return
     */

    @Cacheable(value = "videos",key = "T(com.tanhua.server.interceptor.UserHolder).userId+'_'+#page+'_'+#pagesize")
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        //1.查询redis数据
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        //2.判断redis数据受否存在，判读redis中心数据是否满足本次分页的条数
        List<Video> list = new ArrayList<>();
        int redisPage = 0;
        if (!StringUtils.isEmpty(redisValue)) {
            //如果redis存在数据根据vid查询
            String[] values = redisValue.split(",");
            //判断当前页面的起始条数是否少于组总数
            if ((page-1)*pagesize < values.length){
                List<Long> vids = Arrays.stream(values).skip((page-1)*pagesize).limit(pagesize)
                        .map(e->Long.valueOf(e))
                        .collect(Collectors.toList());
                //5.调用Api根据pid数组查询动态数据
                list = videoApi.findMovementsByVids(vids);
            }
            redisPage = PageUtil.totalPage(values.length,pagesize);
        }
        // 4. 如果redis数据不存在,分页查询视频数据
        if (list.isEmpty()){
            //page的计算规则 传入的页码 - redis查询的总页数
            list = videoApi.queryVideoList(page - redisPage,pagesize);
        }
        //5.提取视频中所有用户的id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //6.查询用户的信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7.构造返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            if (info != null) {
                VideoVo vo = VideoVo.init(info, video);
                //在缓存中查看用户是否已经关注
                String key = "followUser_" + UserHolder.getUserId()+"_"+video.getUserId();
                if (redisTemplate.hasKey(key)){
                    vo.setHasFocus(1);
                }
                vos.add(vo);

            }
        }
        return new PageResult(page,pagesize,0l,vos);
    }

    //关注视频作者
    public void userFocus(Long followUserId) {
        //1、创建FollowUser对象，并设置属性
        FocusUser followUser = new FocusUser();
        followUser.setUserId(UserHolder.getUserId());
        followUser.setFollowUserId(followUserId);
        //2、调用API保存
        videoApi.saveFollowUser(followUser);
        //3、将关注记录存入redis中
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        String hashKey = String.valueOf(followUserId);
        redisTemplate.opsForHash().put(key,hashKey,"1");
    }

    //取消关注视频作者
    public void userUnFocus(Long followUserId) {
        //1、调用API删除关注数据
        videoApi.deleteFollowUser(UserHolder.getUserId(),followUserId);
        //2、删除redis中关注记录
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        String hashKey = String.valueOf(followUserId);
        redisTemplate.opsForHash().delete(key,hashKey);
    }
}

















